package yz.cp.back.auth.sign;

import org.apache.commons.lang3.math.NumberUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import yz.cp.back.common.res.ApiException;
import yz.cp.back.common.utils.SpringUtil;

import java.util.concurrent.TimeUnit;

public class ValidTimeUtils {
    public static StringRedisTemplate redisTemplate;
    public static boolean isValid(String timestamp){
        if(NumberUtils.isDigits(timestamp)){
            Long time=Long.valueOf(timestamp)*1000;
            Long currentTime=System.currentTimeMillis();
            if(Math.abs(currentTime-time)>1000*10*60)
            {
                throw  new ApiException("时间戳超时");
            }else {
                return true;
            }
        }else {
            throw  new ApiException("时间戳格式非法");
        }
    }

    public static boolean isValidNonceStr(String appId,String nonceStr){
        if(redisTemplate==null){
            try {
               redisTemplate = SpringUtil.getBean(StringRedisTemplate.class);
            } catch (Exception e) {
               throw new ApiException("服务端缺少缓存配置");
            }
        }
       String  cacheObj=redisTemplate.opsForValue().get("api-sign:"+appId+":"+nonceStr);
        if(cacheObj!=null){
            throw new ApiException("随机数在有效时间内重复");
        }else {
            redisTemplate.opsForValue().set("api-sign:"+appId+":"+nonceStr,"1",15*60, TimeUnit.SECONDS);
            return true;
        }
    }
}
